package com.adouteam.simple.wechat.base;

import com.adouteam.simple.wechat.tool.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.EntityUtils;

import java.nio.charset.Charset;

/**
 * 服务器IP地址
 *
 * @author buxianglong
 */
public class ServerIP {

    private static ServerIP ME = new ServerIP();

    public static ServerIP getInstance() {
        return ME;
    }

    @SuppressWarnings("unused")
    private String[] ip_list;

    public String[] getIp_list(WechatConstants wechatConstants) {
        return getServerIps(wechatConstants);
    }

    private static String[] getServerIps(WechatConstants wechatConstants) {
        String url = WeixinUrls.replace(WeixinUrls.WEIXIN_SERVER_IPS, wechatConstants, null);
        return HttpUtil.get(url, null, (httpResponse -> {
            String response = EntityUtils.toString(httpResponse.getEntity(), Charset.forName("utf-8"));
            if (StringUtils.isNotBlank(response)) {
                ServerIP serverIP = JSONObject.parseObject(response, ServerIP.class);
                if (serverIP != null) {
                    return serverIP.getIp_list(wechatConstants);
                }
            }
            return new String[0];
        }));
    }
}
